package com.lagou.service.impl;

import com.lagou.dao.TokenDao;
import com.lagou.dao.UserInfoDao;
import com.lagou.pojo.Token;
import com.lagou.pojo.UserInfo;
import com.lagou.service.IAuthCodeServiceClient;
import com.lagou.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private IAuthCodeServiceClient authCodeServiceClient;

    @Override
    public Token register(String email, String password, String code) {
        if (!this.isRegistered(email) &&
                authCodeServiceClient.validateAuthCode(email, code) == 0) {

            UserInfo userInfo = new UserInfo();
            userInfo.setEmail(email);
            userInfo.setPassword(password);
            userInfo.setCreatetime(new Date());
            userInfo.setLogintime(new Date());
            userInfoDao.save(userInfo);

            return generateToken(email, password);
        }
        return null;
    }

    @Override
    public boolean isRegistered(String email) {
        return null != userInfoDao.findFirstByEmail(email);
    }

    @Override
    public Token login(String email, String password) {
        UserInfo userInfo = userInfoDao.findFirstByEmail(email);
        if (userInfo != null && userInfo.getPassword().equalsIgnoreCase(password)) {
            userInfo.setLogintime(new Date());
            userInfoDao.save(userInfo);

            return generateToken(email, password);
        }
        return null;
    }

    @Override
    public String getEmailByToken(String tokenText) {
        Token token = tokenDao.findFirstByToken(tokenText);
        return token == null ? "" : token.getEmail();
    }

    @Override
    public void logout() {

    }

    private Token generateToken(String email, String password) {
        String tokenText = email + password + System.currentTimeMillis();
        UUID uuid = UUID.nameUUIDFromBytes(tokenText.getBytes());

        Token token = new Token();
        token.setEmail(email);
        token.setToken(uuid.toString());
        return tokenDao.save(token);
    }
}
